package com.example.leetcode.custom;

import java.util.List;

/**
 * @author lipengyu
 */
class Solution {
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
        mergeTwoLists(l1, l2, head);
        return head.next;
    }
    public static void mergeTwoLists(ListNode first, ListNode second, ListNode curr) {
        if (first == null) {
            curr.next = second;
            return;
        }
        if (second == null) {
            curr.next = first;
            return;
        }
        if (first.val < second.val) {
            curr.next = first;
            mergeTwoLists(first.next, second, curr.next);
        } else {
            curr.next = second;
            mergeTwoLists(first, second.next, curr.next);
        }
    }

    public static ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
        ListNode curr = head;

        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                curr.next = l1;
                l1 = l1.next;
            } else {
                curr.next = l2;
                l2 = l2.next;
            }
            curr = curr.next;
        }
        curr.next = l1 == null ? l2 : l1;
        return head.next;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);

        System.out.println(mergeTwoLists2(l1, l2));
    }
}